package com.android.svmc.app.mobile.activity;

import java.util.ArrayList;
import java.util.Calendar;

import luyenlv.pro.screen.base.BaseActivity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.svmc.app.mobile.data.DatabaseSource;
import com.android.svmc.app.mobile.model.AccountModel;
import com.android.svmc.app.mobile.tabmanager.TabGroupActivity;
import com.android.svmc.app.mobile.util.CommonDefine;
import com.android.svmc.app.mobile.util.SettingUtils;
import com.android.svmc.app.mobile.util.Validate;
import com.android.svmc.app.mobile.view.FontTextView;

public class ProfileMainActivity extends BaseActivity implements
		OnClickListener, CommonDefine {
	TabGroupActivity parentActivity;
	private TextView title_module;
	private TextView link_signup;
	private EditText username;
	private EditText password;
	private EditText confirm_password;
	private Button birthday;
	private Button login;
	private ToggleButton sex;
	private RelativeLayout rl_signup;
	private ProgressBar progress;
	private boolean isSignUp = false;
	private String date;
	static final int DATE_DIALOG_ID = 1;
	int myprocess = 0;
	private Thread progressCheckLogin;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(getLayout(R.array.diary_login));
		parentActivity = (TabGroupActivity) getParent();
		initUI();
		setClickListen();
		DatabaseSource db = new DatabaseSource(this);
//		for(int i = 0;i < 100; i++){
//			 DiaryModel diary = new DiaryModel();
//			 diary.setTitle("ngay buon : "+i );
//			 diary.setName("anh");
//			 diary.setContent("cha co j buon ca, cu vui di , co vui khong thi bao.Vui ngay len cho anh bao");
//			 diary.setDate("21/09/2013");
//			 db.addDiary(diary);
//		 }
		
	}

	private void initUI() {
		/*
		 * Khai báo view mới.
		 */
		title_module = (TextView) findViewById(R.id.diary_login_txt_logo);
		link_signup = (TextView) findViewById(R.id.diary_login_txt_signup);
		username = (EditText) findViewById(R.id.diary_login_edt_name);
		password = (EditText) findViewById(R.id.diary_login_edt_password);
		confirm_password = (EditText) findViewById(R.id.diary_login_edt_confirm_pass);
		birthday = (Button) findViewById(R.id.diary_login_btn_birthday);
		sex = (ToggleButton) findViewById(R.id.diary_login_toggleButton_sex);
		login = (Button) findViewById(R.id.diary_login_btn_login);
		rl_signup = (RelativeLayout) findViewById(R.id.diary_login_rl_signup_form);
		progress = (ProgressBar) findViewById(R.id.diary_login_progressBar);
		
		/*
		 * Xử lý ,thiết lập style cho view.
		 */
		rl_signup.setVisibility(View.GONE);
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		date = String.valueOf(day) + " /" + String.valueOf(month + 1) + " /"
				+ String.valueOf(year);
		birthday.setText(date);
		FontTextView.setfontFlamenco(title_module, this);
		title_module.setTextSize(TypedValue.COMPLEX_UNIT_SP, 45);
		title_module.setTextColor(this.getResources().getColor(
				R.color.Green_title));
	}

	private void setClickListen() {
		link_signup.setOnClickListener(this);
		username.setOnClickListener(this);
		password.setOnClickListener(this);
		confirm_password.setOnClickListener(this);
		birthday.setOnClickListener(this);
		login.setOnClickListener(this);
		rl_signup.setOnClickListener(this);
		sex.setOnClickListener(this);

	}

	@Override
	public void clearMemory() {
		// TODO Auto-generated method stub

	}

	public boolean addNewAccount(AccountModel account) {
		DatabaseSource db = new DatabaseSource(this);
		long row = db.addAccount(account);
		if (row <= 0) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		progress.setVisibility(View.GONE);	 
		
		
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.diary_login_txt_signup:
			if (isSignUp == false) {
				rl_signup.setVisibility(View.VISIBLE);
				login.setText(this.getString(R.string.button_label_signup));
				link_signup.setText(this.getString(R.string.back_login_screen));
				isSignUp = true;

			} else {
				rl_signup.setVisibility(View.GONE);
				login.setText(this.getString(R.string.button_label_login));
				link_signup.setText(this
						.getString(R.string.textlink_label_signup));
				isSignUp = false;
			}

			break;
		case R.id.diary_login_btn_login:
			if (isSignUp == true) {
				AccountModel acc = new AccountModel();
				if (Validate.validateUsername(username)
						&& Validate
								.validatePassword(password, confirm_password) == CONFIRM_PASSWORD_SUCCESS) {
					acc.setUsername(username.getText().toString());
					acc.setPassword(password.getText().toString());
					acc.setBirtday(birthday.getText().toString());
					if (sex.isChecked()) {
						acc.setSex("Nam");
					} else {
						acc.setSex("Nữ");
					}
					if (checkAccountExits(username.getText().toString()) == ACCOUNT_IS_NOT_EXITS) {
						progress.setVisibility(View.VISIBLE);
						boolean isaddsucess = addNewAccount(acc);
						// Handler handleSplash = new Handler();
						// handleSplash.postDelayed(new loginWellcome(),
						// SPLASH_TIME);
						new Thread(myThread).start();
					} else {
						Toast.makeText(this,
								"UserName này đã tồn tại,Hãy đăng nhập", 1)
								.show();
					}
				} else {
					if (Validate.validateUsername(username) == false) {
						Toast.makeText(this,
								"Tên đăng nhập không được để trống", 0).show();
					} else if (Validate.validatePassword(password,
							confirm_password) == PASSWORD_LENGHT_FAIL) {
						Toast.makeText(this,
								"Password không được ít hơn 6 ký tự", 1).show();
					} else if (Validate.validatePassword(password,
							confirm_password) == CONFIRM_PASSWORD_FAIL) {
						Toast.makeText(this,
								"Hai trường password không trùng nhau", 1)
								.show();
					}
				}

			} else {
				int loginissucessfull = checkLogin(username.getText()
						.toString(), password.getText().toString());
				if (loginissucessfull == LOGIN_SUCCESS) {
					// add code to process login
					progress.setVisibility(View.VISIBLE);
					// new Thread(myThread).start();
					progressCheckLogin = new Thread(myThread);
					progressCheckLogin.start();
				} else if (loginissucessfull == PASSWORD_WRONG) {
					Toast.makeText(this, "Sai mật khẩu", 1).show();
				} else if (loginissucessfull == USERNAME_WRONG) {
					Toast.makeText(this, "Không tồn tại username này", 1)
							.show();
				} else {
					Toast.makeText(this, "Đăng nhập thất bại", 1).show();
				}
			}

			break;
		case R.id.diary_login_btn_birthday:
			showDialog(DATE_DIALOG_ID);
			break;
		default:
			break;
		}

	}

	/**
	 * check (user and pass) is register or not with data in database
	 * 
	 * @param username
	 * @param pass
	 * @return
	 */
	public int checkLogin(String username, String pass) {
		DatabaseSource db = new DatabaseSource(this);
		ArrayList<AccountModel> listacc = db.getAllAccount();
		if (listacc.size() == 0) {
			return USERNAME_WRONG;
		}
		for (AccountModel acc : listacc) {
			if (username.equals(acc.getUsername())
					&& pass.equals(acc.getPassword())) {
				return LOGIN_SUCCESS;
			} else if (pass.equals(acc.getPassword()) == false) {
				return PASSWORD_WRONG;
			} else if (username.equals(acc.getUsername())) {
				return USERNAME_WRONG;
			}

		}
		return LOGIN_FAIL;
	}

	/**
	 * Check user is exits or not.
	 * 
	 * @param username
	 * @return
	 */
	public boolean checkAccountExits(String username) {
		DatabaseSource db = new DatabaseSource(this);
		ArrayList<AccountModel> listacc = db.getAllAccount();
		for (AccountModel acc : listacc) {
			if (username.equals(acc.getUsername())) {
				return ACCOUNT_IS_EXITS;
			}
		}
		return ACCOUNT_IS_NOT_EXITS;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH);
		int day = c.get(Calendar.DAY_OF_MONTH);
		switch (id) {
		case DATE_DIALOG_ID:
			DatePickerDialog datedialog = new DatePickerDialog(
					getDialogContext(),
					new DatePickerDialog.OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view, int year,
								int monthOfYear, int dayOfMonth) {
							Calendar currentCalendar = Calendar.getInstance();
							int maxYear = currentCalendar.get(Calendar.YEAR);
							int maxMonth = currentCalendar.get(Calendar.MONTH);
							int maxDay = currentCalendar
									.get(Calendar.DAY_OF_MONTH);
							int minYear = currentCalendar.get(Calendar.YEAR) - 150;
							int minMonth = currentCalendar.get(Calendar.MONTH);
							int minDay = currentCalendar
									.get(Calendar.DAY_OF_MONTH);

							if (year > maxYear || monthOfYear > maxMonth
									&& year == maxYear || dayOfMonth > maxDay
									&& year == maxYear
									&& monthOfYear == maxMonth) {

								view.updateDate(maxYear, maxMonth, maxDay);
								date = String.valueOf(maxDay) + " /"
										+ String.valueOf(maxMonth + 1) + " /"
										+ String.valueOf(maxYear);
								Toast.makeText(
										ProfileMainActivity.this,
										"Ngày sinh không được lớn hơn ngày hiện tại",
										1).show();
								birthday.setText(date);
							} else if (year < minYear || monthOfYear < minMonth
									&& year == minYear || dayOfMonth < minDay
									&& year == minYear
									&& monthOfYear == minMonth) {
								view.updateDate(minYear, minMonth, minDay);
								date = String.valueOf(dayOfMonth) + " /"
										+ String.valueOf(monthOfYear + 1)
										+ " /" + String.valueOf(year);
								Toast.makeText(
										ProfileMainActivity.this,
										"Bạn có chắc bạn đang trên 150 tuổi ???",
										1).show();
								birthday.setText(date);
							} else {

								view.updateDate(year, monthOfYear, dayOfMonth);
								date = String.valueOf(dayOfMonth) + " /"
										+ String.valueOf(monthOfYear + 1)
										+ " /" + String.valueOf(year);
								birthday.setText(date);
							}
						}
					}, year, month, day);
			return datedialog;
		default:
			break;
		}
		return null;
	}

	private Runnable myThread = new Runnable() {
		int myProgressStatus = 0;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (myProgressStatus < 100) {
				try {
					myHandle.sendMessage(myHandle.obtainMessage());
					Thread.sleep(30);
				} catch (Throwable t) {
				}
			}

		}

		Handler myHandle = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				myProgressStatus++;
				progress.setProgress(myProgressStatus);
				if (myProgressStatus >= 100) {
					if(username.isFocused()){
						SettingUtils.hideSoftKeyboard(username);
					}else if (password.isFocused()) {
						SettingUtils.hideSoftKeyboard(password);
					}else if (confirm_password.isFocused()) {
						SettingUtils.hideSoftKeyboard(confirm_password);
					}
					Intent login = new Intent(ProfileMainActivity.this,
							DiaryListXL.class);
					login.putExtra("username", username.getText().toString());
					login.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
					parentActivity.startChildActivity("DiaryListXL", login);
					myProgressStatus = 0;
					//ProfileMainActivity.this.finish();
				}
			}

		};

	};

	/**
	 * Get context in groupActivity.Use for show dialog
	 * 
	 * @return : context
	 */
	private Context getDialogContext() {
		Context mcontext;
		if (getParent() != null)
			mcontext = getParent();
		else
			mcontext = this;
		return mcontext;
	}
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		
	}


}
